<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="采购单编号" prop="id">
        <el-input v-model="queryParams.id" placeholder="采购单编号" clearable />
      </el-form-item>
      <el-form-item label="采购类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="供应商名称" prop="params[supplierName]">
        <el-input v-model="queryParams['params[supplierName]']" placeholder="请输入供应商名称" clearable />
      </el-form-item>
      <el-form-item label="入库状态" prop="warehouseStatus">
        <el-select v-model="queryParams.warehouseStatus" placeholder="请选择">
          <el-option v-for="item in warehouseOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="date">
        <el-date-picker v-model="queryParams.date" value-format="yyyy-MM-dd" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:order:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:order:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:order:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:order:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="采购单编号" align="center" prop="id" />
      <el-table-column label="采购类型" align="center" prop="type" />
      <el-table-column label="供应商名称" align="center" prop="supplierName" />
      <el-table-column label="验收状态" align="center" prop="statusName" />
      <el-table-column label="入库状态" align="center" prop="warehouseStatusName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']">修改</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改采购单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="100%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="200px">
        <el-form-item label="供应商" prop="supplierId">
          <!-- <el-input v-model="form.supplierId" placeholder="请输入供应商id" /> -->
          <SupplierSelect v-model="form.supplierId" :name="form.supplierName" ref="refSupplierSelect"
            @selected="supplierSelectFun($event, index)" />
        </el-form-item>
        <el-form-item label="采购类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="社会信用代码" prop="creditCode">
          <el-input v-model="form.creditCode" placeholder="请输入社会信用代码" />
        </el-form-item>
        <el-form-item label="加盖公章的营业执照图片" prop="bLicense">
          <!-- <el-input v-model="form.bLicense" placeholder="请输入加盖公章的营业执照图片" /> -->
          <image-upload v-model="form.bLicense" />
        </el-form-item>
        <el-form-item label="食品生产许可证复印件图片" prop="pLicense">
          <!-- <el-input v-model="form.pLicense" placeholder="请输入食品生产许可证复印件图片" /> -->
          <image-upload v-model="form.pLicense" />
        </el-form-item>
        <el-form-item label="食品经营许可证复印件图片或备案证明" prop="fBLicense">
          <!-- <el-input v-model="form.fBLicense" placeholder="请输入食品经营许可证复印件图片或备案证明" /> -->
          <image-upload v-model="form.fBLicense" />
        </el-form-item>
        <!-- <el-form-item label="社会信用代码" prop="creditCode">
          <image-upload v-model="form.creditCode" />
        </el-form-item> -->
        <el-form-item label="身份证正反面复印件图片" prop="idCopy">
          <!-- <el-input v-model="form.idCopy" placeholder="请输入身份证正反面复印件图片" /> -->
          <image-upload v-model="form.idCopy" />
        </el-form-item>
        <el-form-item label="产品合格证明文件url" prop="qualityCert">
          <!-- <el-input v-model="form.qualityCert" placeholder="请输入产品合格证明文件url" /> -->
          <image-upload v-model="form.qualityCert" />
        </el-form-item>
        <el-form-item label="检疫合格证明文件" prop="jyQualityCert">
          <!-- <el-input v-model="form.jyQualityCert" placeholder="请输入检疫合格证明文件" /> -->
          <image-upload v-model="form.jyQualityCert" />
        </el-form-item>
        <el-form-item label="肉品品质检验合格证明文件" prop="rpQualityCert">
          <!-- <el-input v-model="form.rpQualityCert" placeholder="请输入肉品品质检验合格证明文件" /> -->
          <image-upload v-model="form.rpQualityCert" />
        </el-form-item>
        <el-form-item label="猪瘟病毒检测阴性报告文件" prop="vCheckCert">
          <!-- <el-input v-model="form.vCheckCert" placeholder="请输入猪瘟病毒检测阴性报告文件" /> -->
          <image-upload v-model="form.vCheckCert" />
        </el-form-item>
        <el-form-item label="报关单文件" prop="billEntry">
          <!-- <el-input v-model="form.billEntry" placeholder="请输入报关单文件" /> -->
          <image-upload v-model="form.billEntry" />
        </el-form-item>
        <el-form-item label="购物凭证文件" prop="shoppingCert">
          <!-- <el-input v-model="form.shoppingCert" placeholder="请输入购物凭证文件" /> -->
          <image-upload v-model="form.shoppingCert" />
        </el-form-item>
        <!-- <el-form-item label="0正常 1删除" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入0正常 1删除" />
        </el-form-item> -->
        <el-button type="primary" icon="el-icon-plus" @click="addGoods">商品录入</el-button>
        <el-table :data="form.params.products" style="width: 100%">
          <el-table-column label="物品名称" align="center" prop="name"></el-table-column>
          <el-table-column label="数量" align="center" prop="quantity"></el-table-column>
          <el-table-column label="单位" align="center" prop="unit"></el-table-column>
          <el-table-column label="生产日期" align="center" prop="produceTime"></el-table-column>
          <el-table-column label="过期日期" align="center" prop="expireTime"></el-table-column>
          <el-table-column label="食品类型" align="center" prop="fTypeName"></el-table-column>
          <el-table-column label="子类型" align="center" prop="fTypeSubName">
            <template slot-scope="scope">
              {{ (scope.row.fTypeSubName) ? scope.row.fTypeSubName : scope.row.params.fTypeSubName }}
            </template>
          </el-table-column>
          <el-table-column label="是否进口" align="center" prop="whetherImport">
            <template slot-scope="scope">
              <span>{{ (scope.row.whetherImport == '1') ? '是' : '否' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" @click="handleDeleteGoods(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <AddForm ref="addFormRef" @change="addGoodsFun" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/material/purchaseOrder";
import { delGoods } from "@/api/material/purchaseOrderProduct";

import SupplierSelect from '@/components/SupplierSelect/index';
import AddForm from './addForm.vue'

export default {
  name: "Order",
  components: {
    SupplierSelect,
    AddForm
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        date: []
      },
      // 表单参数
      form: {
        params: {
          products: []
        }
      },
      // 表单校验
      rules: {
      },
      options: [
        {
          label: '生产企业采购',
          value: 'Manufacturer'
        },
        {
          label: '经营单位采购',
          value: 'BusinessUnit'
        },
        {
          label: '食用农产品生产者',
          value: 'FoodProducer'
        },
        {
          label: '屠宰企业',
          value: 'Butcher'
        },
        {
          label: '个体工商户',
          value: 'SelfEmployed'
        }
      ],
      warehouseOptions: [
        {
          label: '待入库',
          value: 'ToBeIn'
        },
        {
          label: '完成入库',
          value: 'Complete'
        },
        {
          label: '部分入库',
          value: 'Part'
        }
      ],
      foodTypeOptions: [
        {
          name: '食品',
          val: 'Food'
        },
        {
          name: '食用农产品',
          val: 'FoodFarm'
        },
        {
          name: '食品添加剂',
          val: 'FoodAdd'
        },
        {
          name: '食品相关',
          val: 'FoodRelate'
        }
      ],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    addGoodsFun(e) {
      console.log(e);

      this.form.params.products.push(e)
    },
    addGoods() {
      this.$refs.addFormRef.handleAdd();
    },
    /** 查询采购单列表 */
    getList() {
      this.loading = true;
      const queryForm = Object.assign({}, this.queryParams);
      if (queryForm.date.length > 0) {
        queryForm['params[createTimeStart]'] = queryForm.date[0]
        queryForm['params[createTimeEnd]'] = queryForm.date[1]
      }
      delete queryForm.date;
      listOrder(queryForm).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    supplierSelectFun(row, index) {
      this.form.supplierId = row.id;
      this.$forceUpdate();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        supplierId: null,
        status: null,
        warehouseStatus: null,
        bLicense: null,
        pLicense: null,
        fBLicense: null,
        creditCode: null,
        idCopy: null,
        qualityCert: null,
        jyQualityCert: null,
        rpQualityCert: null,
        vCheckCert: null,
        billEntry: null,
        shoppingCert: null,
        delFlag: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        params: {
          products: []
        }
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        let newRes = Object.assign({}, response.data);
        newRes.params.products = response.data.params.products.map(item => {
          let fTypeName = this.foodTypeOptions.filter(childItem => childItem.val == item.fType)[0].name;
          return {
            ...item,
            fTypeName,
            fTypeSubName: item.fTypeSubName ? item.fTypeSubName : item.params.fTypeSubName
          }
        })
        this.form = response.data;
        this.open = true;
        setTimeout(() => {
          this.$refs.refSupplierSelect.setVal({
            name: this.form.supplierName,
            id: this.form.supplierId
          });
        }, 500)
        this.title = "修改采购单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form);

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //删除商品
    handleDeleteGoods(index, row) {
      if (row.id) {
        delGoods(row.id).then(res => {
          if (res.code == 200) {
            this.form.params.products.splice(index, 1)
            this.$modal.msgSuccess("删除成功");
          }
        })
      } else {
        this.form.params.products.splice(index, 1)
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购单编号为"' + ids + '"的数据项？').then(function () {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('material/purchaseOrder/export', {
        ...this.queryParams
      }, `purchaseOrder_${new Date().getTime()}.pdf`)
    }
  }
};
</script>
